package cn.tedu.fy.pethome.service.impl;

import cn.tedu.fy.pethome.ex.ServiceException;
import cn.tedu.fy.pethome.mapper.CartMapper;
import cn.tedu.fy.pethome.pojo.domain.CartAuthenticationInfo;
import cn.tedu.fy.pethome.pojo.dto.CartAddDTO;
import cn.tedu.fy.pethome.pojo.dto.CartUpdateDTO;
import cn.tedu.fy.pethome.pojo.entity.Cart;
import cn.tedu.fy.pethome.pojo.restful.JsonPage;
import cn.tedu.fy.pethome.pojo.vo.CartStandardVO;
import cn.tedu.fy.pethome.security.AdminDetails;
import cn.tedu.fy.pethome.security.LoginPrincipal;
import cn.tedu.fy.pethome.service.ICartService;
import cn.tedu.fy.pethome.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
@Slf4j
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 新增sku信息到购物车表
     * @param cartDTO
     */
    @Override
    public void addCart(CartAddDTO cartDTO, LoginPrincipal loginPrincipal) {
        log.debug("新增购物车业务逻辑层执行了!!!!!!");
        Long userId = getUserId(loginPrincipal);
        log.debug("输出添加购物车时的用户Id:{}",userId);
        Cart cart = cartMapper.selectExistsCart(userId,cartDTO.getSkuId());
        log.debug("输出是否根据用户Id和skuId查询到购物车数据cart:{}",cart);
        if (cart != null){
            cart.setQuantity(cart.getQuantity() + cartDTO.getQuantity());
            cartMapper.updateQuantityById(cart);
        }else {
            Cart newCart = new Cart();
            BeanUtils.copyProperties(cartDTO,newCart);
            newCart.setUserId(userId);
            log.debug("购物车中没有该数据时，将该数据插入到newCart:{}",newCart);
            cartMapper.saveCart(newCart);
        }
    }

    @Override
    public List<CartStandardVO> listCarts(LoginPrincipal loginPrincipal) {
        // 从SpringSecurity中获得用户id
        Long userId=getUserId(loginPrincipal);
        // 执行查询,会自动在sql语句后生成limit关键字
        List<CartStandardVO> list= cartMapper.selectCartsByUserId(userId);
        // 将分页结果对象PageInfo转换为JsonPage返回
        return list;
    }

    @Override
    public void removeCart(Long id) {
        // 接收mapper执行删除时的返回值,也是删除成功的行数
        int rows = cartMapper.deleteCartsByIds(id);
        if(rows==0){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"您要删除的商品不存在");
        }
    }

    @Override
    public void removeAllCarts(LoginPrincipal loginPrincipal) {
        Long userId=getUserId(loginPrincipal);
        int rows = cartMapper.deleteCartsByUserId(userId);
        if(rows==0){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"您的购物车中没有商品");
        }
    }

    @Override
    public void removeUserCarts(Cart cart) {
        cartMapper.deleteCartByUserIdAndSkuId(cart);
    }

    @Override
    public void updateQuantity(CartUpdateDTO cartUpdateDTO) {
        // 这个类型中包含id和quantity属性
        Cart cart=new Cart();
        BeanUtils.copyProperties(cartUpdateDTO,cart);
        // 实施持久层调用
        cartMapper.updateQuantityById(cart);
    }

    /**
     * 从SpringSecurity用户容器获取用户信息
     * @return
     */
    public CartAuthenticationInfo getUserInfo(LoginPrincipal loginPrincipal){
        log.debug("getUserInfo执行了");
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext()
                .getAuthentication();
        log.debug("解析authenticationToken:{}",authenticationToken);
        log.debug("====Authorities输出,{}",authenticationToken.getAuthorities());
        if (authenticationToken == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"没有登录信息");
        }

        // 如果authenticationToken不为空,获得其中的用户信息
        log.debug("getUserInfo中获得id:{},userName:{}",loginPrincipal.getId(),loginPrincipal.getUsername());
        CartAuthenticationInfo cartAuthenticationInfo = new CartAuthenticationInfo();
        cartAuthenticationInfo.setId(loginPrincipal.getId());
        cartAuthenticationInfo.setUsername(loginPrincipal.getUsername());

        log.debug("cartAuthenticationInfo中的id：{}", cartAuthenticationInfo.getId());
        log.debug("cartAuthenticationInfo中的用户名：{}", cartAuthenticationInfo.getUsername());
        Collection<GrantedAuthority> authorities = authenticationToken.getAuthorities();
        log.debug("Collection类型的authorities{}",authorities);
        cartAuthenticationInfo.setAuthorities((List)authorities);
        log.debug("登录成功的cartAuthenticationInfo管理员权限：{}", cartAuthenticationInfo.getAuthorities());

        String authoritiesString = JSON.toJSONString(authorities);
        log.debug("将管理员权限转换为JSON：{}", authoritiesString);

        log.debug("输出cartAuthenticationInfo:{}",cartAuthenticationInfo);
        // 返回登录用户信息
        return cartAuthenticationInfo;
    }

    /**
     * 获取当前用户的id
     * @return
     */
    public Long getUserId(LoginPrincipal loginPrincipal){
        return getUserInfo(loginPrincipal).getId();
    }
}
